package org.jiajin2coding.reggie.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.jiajin2coding.reggie.common.ResultVO;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Guo Jinhua (jiajin2coding)
 * @version 1.0.0
 * @className LoginCheckFilter
 * @description 登录拦截器，用于检查用户是否已经完成登录
 * @date 2023-10-26
 */
@Slf4j
@WebFilter(filterName = "/loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    // 路径匹配器，同时支持通配符
    public static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    private static final String CONTEXT_URI = "/reggie-take-out";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1. 获取本次请求的 URI
        String requestURI = request.getRequestURI();
        log.info("进入拦截器 拦截到请求 {}", requestURI);
        String[] urls = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
        };

        // 2. 判断本次请求是否需要处理
        boolean check = checkUri(urls, requestURI);

        // 3. 如果不需要处理，则直接放行
        if (check) {
            log.info("本次请求无需处理 {}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        // 4. 判断登录状态，如果已登录，则直接放行
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        if (employeeId != null) {
            log.info("用户已登录，登录用户ID {}", employeeId);
            filterChain.doFilter(request, response);
            return;
        }

        // 5. 如果未登录则返回登录界面，通过输出流方式向客户端页面响应数据
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(ResultVO.error("NOTLOGIN")));
        return;

    }

    /**
     * 路径匹配：检查本次请求是否需要放行
     * @param requestURI
     * @return
     */
    public boolean checkUri(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = ANT_PATH_MATCHER.match(CONTEXT_URI + url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }

}
